import { useEffect, useState } from 'react';
import { useRouteError } from 'react-router-dom';
import axios from 'axios';
import { setUserInfo } from './user-info';
import { initHttpClient } from '@/http';
import { initStorage } from './storage';
import { setToken } from './token';
import type { IConfig } from '../config/types';
import { setConfig } from './utils';

export const NoMatch = () => <div>404</div>;

export const RootErrorBoundary = () => {
  const error = useRouteError() as Error;

  useEffect(() => {
    console.warn(error);
  }, [error]);

  return (
    <div>
      <div>报错了</div>
      <p>控制台中查看详细报错信息。</p>
    </div>
  );
};

export const useRoutePerpare = () => {
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    console.log('版本号：', import.meta.env.SM_APP_VERSION);
    axios.get<IConfig>(`config/config.json?=${Date.now()}`).then(async (res) => {
      if (res.data) {
        setLoading(false);
        setConfig(res.data);
        const { apiBaseUrl } = res.data.serviceSettings;
        initHttpClient({ baseURL: apiBaseUrl });
        const storagePrefix = apiBaseUrl.includes('http') ? new URL(apiBaseUrl).pathname.replace(/\//g, '') : apiBaseUrl.replace(/\//g, '');
        initStorage({ prefix: storagePrefix });
        setToken('localdev');
        setUserInfo({ id: 'localdev', name: '本地开发' });
      }
    });
  }, []);
  return { loading };
};
